package cn.xyy.system.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import cn.xyy.common.domain.system.auth.UserInfo;
import cn.xyy.common.domain.system.auth.UserInfoVO;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.jdbc.BaseDao;
import cn.xyy.common.domain.mvc.Page;

/**
 * 用户数据持久层
 * 
 * @author xyy
 *
 */
@Repository
public class UserDao extends BaseDao {

	public Page<UserInfo> selectPage(UserInfoVO user) {
		List<UserInfo> list = super.select(
				getSqlPageHandle().handlerPagingSQL(userPageSql(user, 0), user.getPage(), user.getLimit()), null,
				UserInfo.class);
		int count = super.getJdbcTemplate().queryForObject(userPageSql(user, 1), null, Integer.class);
		Page<UserInfo> page = new Page<UserInfo>(list, count, user.getLimit(), user.getPage());
		return page;
	}

	private String userPageSql(UserInfoVO user, int type) {
		StringBuilder sql = new StringBuilder();
		if (type == 0) {
			sql.append(
					" select  u.uid,u.username,u.realName,u.password,u.mobile,u.email,u.create_time as createTime,u.creator,u.status,u.dept_id as deptId,d.name as deptName,u.job_id as jobId,j.name as jobName from t_sys_user u  ");
			sql.append(" left join t_sys_dept d on d.dept_id=u.dept_id ");
			sql.append(" left join t_sys_job j on j.job_id=u.job_id ");
		} else {
			sql.append(" select count(*) from t_sys_user u  ");
			sql.append(" left join t_sys_dept d on d.dept_id=u.dept_id ");
			sql.append(" left join t_sys_job j on j.job_id=u.job_id ");
		}
		sql.append(" where 1=1");

		if (StringUtils.isNotBlank(user.getUsername())) {
			sql.append(" and u.username like '%").append(user.getUsername().trim() + "%' ");
		}
		if (StringUtils.isNotBlank(user.getRealName())) {
			sql.append(" and u.realName like '%").append(user.getRealName().trim() + "%' ");
		}
		if (StringUtils.isNotBlank(user.getMobile())) {
			sql.append(" and u.mobile like '%").append(user.getMobile().trim() + "%' ");
		}
		if (user.getDeptId() != null && !"2".equals(user.getDeptId())) {
			sql.append(" and u.dept_id=" + user.getDeptId() + "");
		}
		if (user.getStatus() != null) {
			sql.append(" and u.status=" + user.getStatus() + "");
		}
		if (type == 0) {
			if (StringUtils.isNotBlank(user.getSidx())) {
				if ((user.getSord().trim().equalsIgnoreCase("asc"))) {
					sql.append(" order by " + user.getSidx().split(" ")[0] + " asc");
				} else {
					sql.append(" order by " + user.getSidx().split(" ")[0] + " desc");
				}
			} else {
				sql.append(" order by createTime desc");
			}
		}
		return sql.toString();
	}

	public int updateState(String uid, int state) {
		StringBuilder sql = new StringBuilder();
		sql.append("update t_sys_user set state=? where uid=?");
		return super.insertOrUpdateOrDelete(sql.toString(), new Object[] { state, uid });
	}

}
